﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Net.NetworkInformation;
using MiruPublic;

namespace MangaKurosagi
{
    public partial class ViewDetails : PhoneApplicationPage
    {
        Popup popup = new Popup();

        public ViewDetails()
        {
            InitializeComponent();

            ControlManager.ShowLoading(popup, "Đang tải các tập truyện mới nhất .\nBạn hãy đợi tí xíu nhé...", true);
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            
            string PinStart = "";

            NavigationContext.QueryString.TryGetValue("Pinstart", out PinStart);

            if(PinStart=="true")
            {
                string Title;
                string Url;

                NavigationContext.QueryString.TryGetValue("RootTitle", out Title);
                NavigationContext.QueryString.TryGetValue("RootUrl", out Url);

                Global.StoriesSelected = new Stories() { Title=Title,Url=Url,Update=true};
            }

            if (Global.StoriesSelected.Update == true)
            {
                Global.StoriesSelected.Update = false;

                UpdateControls();
            }
            

            checkLike.IsChecked = false;

            if (Global.ListStoriesLike.Where(like => like.Title == title.Text).Count() > 0)
                checkLike.IsChecked = true;
        }

        private void UpdateControls()
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show("Không thể kết nối mạng \n Kiểm tra wifi/cellular và truy cập lại để tải truyện");

                popup.IsOpen = false;

                return;
            }
            Global.StoriesSelected.GetListChap();

            Global.StoriesSelected.GetListChapCompleted += (s, args) =>
            {
                title.Text = args.info.Title;
                Global.StoriesSelected.Title = title.Text;
                description.Text = args.info.Description;
                Global.StoriesSelected.Description = description.Text;
                thumbnail.Source = new BitmapImage(new Uri(args.info.UrlImage));
                Global.StoriesSelected.UrlImage = args.info.UrlImage;

                popup.IsOpen = false;

                listChap.ItemsSource = args.listResult;
            };
        }


        /// <summary>
        /// Thực hiện sử lý việc chọn chap
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listChap_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ItemChap item = listChap.SelectedItem as ItemChap;

            if (item != null)
            {
                Global.ChapSelected = new Chap() { Url = item.Url, Title = item.Title, Update = true ,index=item.index};
                NavigationService.Navigate(new Uri("/ReadChap.xaml",UriKind.Relative));
            }
        }

        

        private void BtnDownload_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Chức năng đang được thực hiện");
            //DownloadStories download = new DownloadStories();
            //download.DownloadStorie(Global.StoriesSelected);
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            var newTile = new StandardTileData()
            {
                Title = Global.StoriesSelected.Title,
                BackgroundImage = new Uri("/Background.png", UriKind.RelativeOrAbsolute),
                BackBackgroundImage = new Uri(Global.StoriesSelected.UrlImage, UriKind.Absolute),//new Uri("/Background.png", UriKind.RelativeOrAbsolute),
                BackContent = "Manga Online",
                // Count = 42,

            };
            string navigate = "";
            navigate += "Pinstart=true";
           // navigate += "&Description=" + Global.StoriesSelected.Description;
            navigate += "&RootTitle=" + Global.StoriesSelected.Title;
            navigate += "&RootUrl=" + HttpUtility.UrlEncode(Global.StoriesSelected.Url);
           // navigate += "&UrlImage=" + HttpUtility.UrlEncode(Global.StoriesSelected.UrlImage);

            ShellTile.Create(new Uri("/ViewDetails.xaml?" + navigate, UriKind.Relative), newTile);
        }

        private void checkLike_Click(object sender, RoutedEventArgs e)
        {
            if (checkLike.IsChecked == true)
            {
                if (Global.ListStoriesLike.Where(s => s.Title == Global.StoriesSelected.Title).Count() <= 0)
                {
                    Global.ListStoriesLike.Add(Global.StoriesSelected);
                    StorageHelper.SaveFarviousXML("StoriesFarvious.xml", Global.ListStoriesLike);
                }
            }
            else
            {
                var result = Global.ListStoriesLike.Where(s => s.Title == Global.StoriesSelected.Title);

                if (result != null)
                {
                    Global.ListStoriesLike.Remove(result.First());
                    StorageHelper.SaveFarviousXML("StoriesFarvious.xml", Global.ListStoriesLike);
                }
            }
        }
    }
}